<template>
  <view class="options-popup">
    <!-- 标题栏 -->
    <view class="popup-header">
      <text class="date-text">{{ formatDisplayDate(date) }}</text>
    </view>

    <!-- 事件列表 -->
    <scroll-view 
      class="events-list" 
      scroll-y
      v-if="events && events.length > 0"
    >
      <view 
        v-for="(event, index) in events" 
        :key="index"
        class="event-wrapper"
      >
        <view 
          class="event-item"
          @tap="toggleEventOptions(index)"
        >
          
          <text class="event-title">{{ event.title }}</text>
          <text class="event-arrow" :class="{ 'rotated': selectedEventIndex === index }">▼</text>
        </view>
        
        <!-- 选项面板 -->
        <view class="event-options" v-show="selectedEventIndex === index">
          <view class="option-item" @tap="handleEdit(event)">
            <text class="option-icon">✏️</text>
            <text class="option-text">编辑</text>
          </view>
          <view class="option-item delete" @tap="handleDelete(event)">
            <text class="option-icon">🗑️</text>
            <text class="option-text">删除</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 无事件提示 -->
    <view v-else class="no-events">
      <text>当前日期暂无安排</text>
    </view>

    <!-- 新增日程按钮 -->
    <view class="add-button-container">
      <button class="add-button" @tap="handAdd()">
        <text class="add-text">新建安排</text>
      </button>
    </view>

    <!-- 弹窗 -->
    <uni-popup ref="popupRef" type="center" backgroud-color="#fff">
      <planForm :eventData="selectEvent" @on-back="closePopup()" @on-success="popupRef?.open()">
      </planForm>
    </uni-popup>
    

  </view>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import type { CalendarEvent } from '@/types/calendar'
import { deleteEventInfoAPI } from '@/services/calendar';
import planForm from '@/pages/form/planForm.vue';


//接收从父组件传入的数据
interface Props {
  date: string
  events?: CalendarEvent[]
}

const props = withDefaults(defineProps<Props>(), {
  events: () => []
})

const emit = defineEmits(['add-event', 'edit-event', 'delete-event'])

//控制弹窗显示
const popupRef = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()

const selectEvent = ref<CalendarEvent>({} as CalendarEvent)

const selectedEventIndex = ref<number | null>(null)

const toggleEventOptions = (index: number) => {
  selectedEventIndex.value = selectedEventIndex.value === index ? null : index
}

const handleEdit = (event: CalendarEvent) => {
  selectEvent.value = event
  popupRef.value?.open() 
}

const handleDelete = async (event: CalendarEvent) => {
  uni.showModal({
    title: '确认删除',
    content: '是否确认删除该日程？',
    success: async(res) => {
      if (res.confirm) {
        try {
          const result = await deleteEventInfoAPI(event.id)
          if (result.result) {
            uni.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 1500
            })
            // 重置选中状态
            selectedEventIndex.value = null
            // 触发父组件的删除事件，通知父组件更新数据
            emit('delete-event')
            
            // 获取当前页面实例
            const pages = getCurrentPages()
            const currentPage = pages[pages.length - 1]
            // 调用页面的刷新方法
            if (currentPage && currentPage.$vm && currentPage.$vm.initCalendar) {
              currentPage.$vm.initCalendar()
            }
          }
        } catch (error) {
          uni.showToast({
            title: '删除失败',
            icon: 'error',
            duration: 1500
          })
        }
      }
    }
  })
}

const formatDisplayDate = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
}

const handAdd = () => {
  selectEvent.value.id = ''
  selectEvent.value.beginDate = props.date
  selectEvent.value.endDate = props.date
  selectEvent.value.title = ''
  selectEvent.value.description = ''
  popupRef.value?.open()
}

const closePopup = () => {
  popupRef.value?.close()
  
}
</script>

<style scoped>
.options-popup {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 30rpx;
  min-height: 400rpx;
  position: relative;
  display: flex;
  flex-direction: column;
  height: 80vh;
}

.popup-header {
  text-align: center;
  padding-bottom: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.events-list {
  flex: 1;
  margin: 20rpx 0;
  max-height: 60vh;
}

.event-wrapper {
  border-bottom: 1rpx solid #eee;
}

.event-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  position: relative;
}


.event-title {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.event-arrow {
  font-size: 24rpx;
  color: #999;
  transition: transform 0.3s ease;
}

.event-arrow.rotated {
  transform: rotate(180deg);
}

.event-options {
  background-color: #f8f8f8;
  padding: 10rpx 20rpx;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.option-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
}

.option-item:active {
  background-color: #f0f0f0;
}

.option-icon {
  margin-right: 20rpx;
  font-size: 32rpx;
}

.option-item.delete {
  color: #ff3b30;
}

.add-button-container {
  padding: 40rpx 20rpx;
  position: sticky;
  bottom: 0;
  background-color: #fff;
}

.add-button {
  background-color: #007AFF;
  color: #fff;
  border-radius: 10rpx;
  padding: 20rpx 0;
  width: 100%;
  border: none;
}

.add-text {
  font-size: 30rpx;
}

.no-events {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 28rpx;
}
</style>